package com.zhiliao.common.db.impl;

import com.zhiliao.common.db.DbTableAssistant;
import com.zhiliao.common.db.kit.MysqlFiledUtil;
import com.zhiliao.common.exception.SystemException;
import com.zhiliao.common.utils.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Description:mysql
 *
 * @author Jin
 * @create 2017-04-18
 **/
@Component
@Scope("prototype")
public class MysqlDbTableAssistant implements DbTableAssistant<MysqlDbTableAssistant> {

    private final static Logger log = LoggerFactory.getLogger(MysqlDbTableAssistant.class);

    /**
     * 创建表 开始
     */
    private final static String CREATE_TABLE_BEGIN = "CREATE TABLE `{table}` (";

    /**
     * 创建表 结束
     */
    private final static String CREATE_TABLE_END = ") ";

    /**
     * 删除表
     */
    private final static String DROP_TABLE = "DROP TABLE `{table}` ";

    /**
     * 编辑表
     */
    private final static String ALTER_TABLE_BEGIN = "ALTER TABLE `{table}`";

    private final static String CHANGE_COLUMN = " CHANGE COLUMN ";

    private final static String ADD_COLUMN = " ADD COLUMN ";

    private final static String DROP_COLUMN = " DROP COLUMN ";

    private String sqlHead = "";

    private String sqlBody="";

    private String sqlFoot="";

    private void init(){

        this.sqlHead = "";

        this.sqlBody = "";

        this.sqlFoot = "";
    }

    @Override
    public MysqlDbTableAssistant create() {
        this.init();
        this.sqlHead = CREATE_TABLE_BEGIN;
        this.sqlFoot = CREATE_TABLE_END;
        return this;
    }

    @Override
    public MysqlDbTableAssistant edit() {
        this.init();
        this.sqlHead = ALTER_TABLE_BEGIN;
        return this;
    }

    @Override
    public MysqlDbTableAssistant delete() {
        this.init();
        this.sqlHead = DROP_TABLE;

        return this;
    }

    @Override
    public String builderSQL() {
        String sql = this.sqlHead + this.sqlBody + this.sqlFoot;
        log.info(sql);
        return sql;
    }

    @Override
    public MysqlDbTableAssistant tableName(String tableName) {
        this.sqlHead = this.sqlHead.replace("{table}",tableName);
        return this;
    }

    @Override
    public MysqlDbTableAssistant initColumn(String columnName, M columnType, Integer length,boolean autoIncrement, String defaultValue, boolean isNotNull,boolean isPrimaryKey) {
        /*判断字段是否允许设置长度*/
        if(MysqlFiledUtil.isCharTextFiled(columnType)) {
            this.sqlBody = " `"+columnName+"`" + columnType+"("+length+")";
        } else {
            this.sqlBody = " `"+columnName+"`" + columnType;
        }
        /*判断字段是否不为空*/
        if(isNotNull) {
            this.sqlBody+=" NOT null";
        }
        /*判断字段是否允许为空*/
        if (!autoIncrement) {
            if(!isNotNull) {
                this.sqlBody+=" NULL ";
            }
            this.sqlBody += " DEFAULT " +  (StrUtil.isBlank(defaultValue)?null:"'"+defaultValue+"'");
        } else { /* 判断字段类型是否支持自动增长 */
            if(MysqlFiledUtil.isAutoIncrementFiled(columnType)) {
                if (!isNotNull) {
                    this.sqlBody += " NOT null";
                }
                this.sqlBody += " AUTO_INCREMENT";
            }
        }
        /*是否为主键*/
        if(isPrimaryKey) {
            this.sqlBody +=" , PRIMARY KEY (`"+columnName+"`) ";
        }
        return this;
    }

    @Override
    public MysqlDbTableAssistant addColumn(String columnName,M columnType,Integer length, boolean autoIncrement,String defaultValue,boolean isNotNull,boolean isPrimaryKey) {
        this.sqlBody = ADD_COLUMN;
        /*判断字段是否允许设置长度*/
        if(MysqlFiledUtil.isCharTextFiled(columnType)){
            this.sqlBody += " `"+columnName+"` " + columnType+"("+length+")";
        } else {
            this.sqlBody += " `"+columnName+"` " + columnType;
        }
        /*判断字段是否不为空*/
        if(isNotNull) {
            this.sqlBody+=" NOT NULL";
        }
        if(autoIncrement) {
            /* 判断字段类型是否支持自动增长 */
            if(MysqlFiledUtil.isAutoIncrementFiled(columnType)) {
                if (!isNotNull) {
                    this.sqlBody += " NOT null";
                }
                this.sqlBody += " AUTO_INCREMENT";
            }
        }else {
            /*判断字段是否允许为空*/
            if(!isNotNull) {
                this.sqlBody+=" NULL ";
            }
            if(!MysqlFiledUtil.isNotDefaultValue(columnType)) {
                /*判断字段类型是否为数值型*/
                if(MysqlFiledUtil.isAutoIncrementFiled(columnType)&& !StringUtils.isNumeric(defaultValue))
                    /*todo 有待做日期类型验证*/ {
                    throw new SystemException("数值型字段不能设置默认值为字符");
                }
                this.sqlBody += " DEFAULT " + (StrUtil.isBlank(defaultValue) ? null : "'" + defaultValue + "'");
            }
        }
        /*是否为主键*/
        if(isPrimaryKey) {
            this.sqlBody +="  , ADD PRIMARY KEY (`"+columnName+"`) ";
        }
        return this;
    }

    @Override
    public MysqlDbTableAssistant changeColumn(String columnName,String newColumnName,M columnType,Integer length,boolean autoIncrement,String defaultValue,boolean isNotNull) {
        this.sqlBody = CHANGE_COLUMN;
        /*判断字段是否允许设置长度*/
        if(MysqlFiledUtil.isCharTextFiled(columnType)) {
            this.sqlBody += " `"+columnName+"` " +" `"+newColumnName+"` "+ columnType+"("+length+")";
        } else {
            this.sqlBody += " `"+columnName+"` " +" `"+newColumnName+"` " + columnType;
        }
        if(isNotNull) {
            this.sqlBody+=" NOT null";
        }
        if(autoIncrement) {
            /* 判断字段类型是否支持自动增长 */
            if(MysqlFiledUtil.isAutoIncrementFiled(columnType)) {
                if (!isNotNull) {
                    this.sqlBody += " NOT null";
                }
                this.sqlBody += " AUTO_INCREMENT ;";
            }
        }else {
            /*判断字段是否允许为空*/
            if(!isNotNull) {
                this.sqlBody+=" NULL ";
            }
            if(MysqlFiledUtil.isNotDefaultValue(columnType)) {
                this.sqlBody += " DEFAULT " +  (StrUtil.isBlank(defaultValue)?null:"'"+defaultValue+"'")+";";
            }
        }

        return this;
    }

    @Override
    public MysqlDbTableAssistant dropColumn(String columnName,boolean isPrimaryKey) {
        this.sqlBody=DROP_COLUMN +"`"+columnName+"`";
        return this;
    }


    @Override
    public MysqlDbTableAssistant addIndex(String cloumnName, Integer length) {
        return null;
    }

    @Override
    public MysqlDbTableAssistant engine(String engineName) {
        this.sqlFoot+=" ENGINE="+engineName+" ";
        return this;
    }

    @Override
    public MysqlDbTableAssistant charSet(String charset) {
        this.sqlFoot+=" DEFAULT CHARSET="+charset+" ";
        return this;
    }


}
